package com.micangcaihang.micang;


import android.content.Context;
import android.support.multidex.MultiDex;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.lzy.okgo.model.HttpHeaders;
import com.micangcaihang.common.base.app.BaseApp;
import com.micangcaihang.micang.entity.UserInfoSp;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.crashreport.CrashReport;

import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import okhttp3.OkHttpClient;

/**
 * <pre>
 *     author : Fandy
 *     e-mail : fandayongfly@gmail.com
 *     time   : 2017/7/18
 *     update : 2017/7/18
 *     desc   : APP主程序
 *     version: 1.0
 * </pre>
 */
public class App extends BaseApp {
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        UserInfoSp.getInstance().getAccess();
        initOkGo();
        initBugly();
    }

    private void initBugly() {
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(this);
        strategy.setAppChannel("MiCang");  //设置渠道
        strategy.setAppVersion("1.0.0");      //App的版本
        strategy.setAppPackageName("com.micangcaihang.micang");  //App的包名
        Bugly.init(getApplicationContext(), "a78ec78737", BuildConfig.LOG_DEBUG, strategy);
    }

    private void initOkGo() {
        HttpHeaders headers = new HttpHeaders();
        headers.put("token", UserInfoSp.getInstance().getToken());    //header不支持中文，不允许有特殊字符
        headers.put("userid", UserInfoSp.getInstance().getUserid());
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("MiCang");
        //log打印级别，决定了log显示的详细程度
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
        //log颜色级别，决定了log在控制台显示的颜色
        loggingInterceptor.setColorLevel(Level.INFO);
        if (BuildConfig.LOG_DEBUG) {
            builder.addInterceptor(loggingInterceptor);
        }
        //全局的读取超时时间
        builder.readTimeout(1000L, TimeUnit.MILLISECONDS);
        //全局的写入超时时间
        builder.writeTimeout(1000L, TimeUnit.MILLISECONDS);
        //全局的连接超时时间
        builder.connectTimeout(1000L, TimeUnit.MILLISECONDS);
        OkGo.getInstance().init(this)                           //必须调用初始化
                .setOkHttpClient(builder.build())               //建议设置OkHttpClient，不设置会使用默认的
                .setRetryCount(3)
                .addCommonHeaders(headers);                               //全局统一超时重连次数，默认为三次，那么最差的情况会请求4次(一次原始请求，三次重连请求)，不需要可以设置为0
    }
}
